package io.github.talelin.latticy.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import io.github.talelin.autoconfigure.exception.ForbiddenException;
import io.github.talelin.latticy.common.mybatis.Page;
import io.github.talelin.latticy.dto.rule.ruleValue.RuleValueDTO;
import io.github.talelin.latticy.model.RuleValueDO;
import io.github.talelin.latticy.mapper.RuleValueMapper;
import io.github.talelin.latticy.service.RuleValueService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author generator@wulongbo
 * @since 2022-08-23
 */
@Service
public class RuleValueServiceImpl extends ServiceImpl<RuleValueMapper, RuleValueDO> implements RuleValueService {

    @Override
    public boolean addRuleValue(RuleValueDTO dto) {
        checkRuleValueExistByKeyAndValue(dto);
        return this.save(new RuleValueDO(dto));
    }

    @Override
    public boolean updateRuleValueById(RuleValueDTO validator, Integer id) {
        checkRuleValueExistByKeyAndValue(validator);
        return this.updateById(new RuleValueDO(validator, id));
    }

    @Override
    public boolean deleteRuleValueById(Integer id) {
        return this.baseMapper.deleteById(id) > 0;
    }

    @Override
    public List<RuleValueDO> getRuleValueList(Integer ruleKeyId) {
        QueryWrapper<RuleValueDO> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(RuleValueDO::getRuleKeyId, ruleKeyId);
        return this.list(wrapper);
    }

    @Override
    public RuleValueDO getRuleValueById(Integer id) {
        return this.getById(id);
    }

    @Override
    public IPage<RuleValueDO> getRuleValuePage(Integer ruleKeyId, Integer page, Integer count) {
        QueryWrapper<RuleValueDO> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(RuleValueDO::getRuleKeyId,ruleKeyId);
        Page<RuleValueDO> pager = new Page<>(page, count);
        return this.baseMapper.selectPage(pager, wrapper);
    }

    private void checkRuleValueExistByKeyAndValue(RuleValueDTO dto) {
        QueryWrapper<RuleValueDO> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(RuleValueDO::getRuleKeyId,dto.getRuleKeyId()).eq(RuleValueDO::getValue, dto.getValue());
        int count = this.count(wrapper);
        if (count > 0) {
            throw new ForbiddenException(18800);
        }
    }

}
